#coding=utf-8
#!/usr/bin/python2.7.5
"""
当日公告统计信息发送模块
"""
import sys
import urllib
import Scrapy
import urllib2
import requests
import json
import time
import logging
import os
reload(sys)
sys.setdefaultencoding('utf-8')

logFilePath = '/opt/spider/zhaobiaowang/log.log' #到服务器上写成绝对路径
biddingIdSendLogPath = '/opt/spider/zhaobiaowang/bidding.log' #到服务器上写成绝对路径
weixinReciver = ['亿阳-四川-颜露','亿阳-四川-曾昭国','亿阳-四川-销售-姚瑞','亿阳-四川-蒲素','亿阳-四川-张华','亿阳-四川-崔勇','亿阳-四川-徐巍','亿阳-四川-赵子银','亿阳-四川-销售-杨安东','亿阳-四川-李良国']
#weixinReciver = []
# toMail = '1299269184@qq.com,yanchanggang2015@boco.com.cn,pusu@boco.com.cn,cuiyong@boco.com.cn,zengzhaoguo@boco.com.cn,yaorui@boco.com.cn,zhanghua@boco.com.cn,yangandong@boco.com.cn,zhaoziyin@boco.com.cn,xuwei@boco.com.cn'
toMail = '1299269184@qq.com'

logging.basicConfig(level=logging.INFO,
                format='[%(asctime)s %(filename)s line:%(lineno)d %(levelname)s] %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                filename=logFilePath,
                filemode='a')


weixinUrl = "http://139.199.82.220:5000/wx"
msgInfo='您好！\n中国移动采购与招标网%s共计发布%s条公告，与公司业务关键字匹配的公告共计%s条，不匹配的公告共%s条；\n与公司业务关键字匹配的公告，已经通过微信和邮件发送，请注意查收；'

mailUrl = 'http://139.199.82.220:8380/mail'


def doMain():
    sumInfo=Scrapy.getTodayInfoNum()
    mathInfo=getMathInfo()
    noMathInfo=sumInfo-mathInfo
    sumInfo=str(sumInfo)
    print u"今天发布总条数:"+sumInfo
    mathInfo=str(mathInfo)
    print u"今天发布匹配数:"+mathInfo
    noMathInfo=str(noMathInfo)
    print u"今天发布不匹配数:"+noMathInfo
    info ={'sumInfo':sumInfo,'mathInfo':mathInfo,'noMathInfo':noMathInfo}
    logging.info("today's publish information:" + sumInfo)
    logging.info("today's match information:" + mathInfo)
    logging.info("today's not match information:" + noMathInfo)
    try:
        sendWeixin(info)
        logging.info("sendding wechat message success")
    except Exception,e:
        print e
        logging.info("sendding wechat message fail")
        logging.info(e)

def getMathInfo():
    i=0
    toDay=time.strftime('%Y-%m-%d',time.localtime(time.time()))
    if not os.path.exists(biddingIdSendLogPath):
        return 
    with open(biddingIdSendLogPath, 'r') as f:
        for line in f.readlines():
            info = line.strip().split(" ")
            if toDay == info[0]:
                i=i+1
        return i


def sendWeixin(info): 
    for user in weixinReciver:
        wxmsg = msgInfo%(time.strftime('%Y-%m-%d',time.localtime(time.time())), info['sumInfo'], info['mathInfo'], info['noMathInfo'])
        param = {'wxmsg': wxmsg.decode('utf-8'), 'wxuser': user.decode('utf-8')}
        print wxmsg.decode('utf-8')  #乱码
        requests.post(weixinUrl, param)



if __name__ == '__main__':
    logging.info("==========Today's Information sendding start!=========")
    doMain()
    logging.info("==========Today's Information sendding end!=========")
